<?php
/**
 * Excel 文档导入
 */
namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use Schema;
use Storage;

class ImportController extends Controller
{
    protected $model;
    protected $file;

    public function import(Request $request){
        $this->file = $request->file('file');
        $this->model = $request->get('model');
        //$newFileName = md5(microtime()) . '.' .$ext;
        //$folder = 'excels/'.date('Y-m-d');
        //$this->dirCheck($folder);
        if(!$this->extCheck()){
            return response()->json('仅接受Excel文档类型');
        }
        if ($this->file->isValid()){
            //$path = $file->storeAs($folder,$newFileName);
            $data = $this->loadExcel($this->file->path());
            $list = $this->validateData($data);
            if($this->saveToDatabase($data))
                return response()->json(['msg'=>'导入成功','list'=>$list,'data'=>$data]);
            else
                return response()->json(['msg'=>'导入失败','list'=>$list,'data'=>$data]);
        }
    }

    protected function loadExcel($path){
        Excel::load($path, function($reader)use(&$data) {
            $data = $reader->get()->toArray();
        });
        return $data;
    }

    protected function dirCheck($folder){
        if(!Storage::exists($folder)){
            Storage::makeDirectory($folder);
        }
    }

    protected function extCheck(){
        $allowed_ext = ["xls", "xlsx", "cvs"];
        $ext=$this->file->getClientOriginalExtension();
        return in_array($ext,$allowed_ext)?true:false;
    }

    protected function validateData($data){
        $column = Schema::getColumnListing($this->model);
        $collection = collect($data[0]);
        return $collection->keys();
    }

    protected function saveToDatabase($data){
        return DB::table($this->model)->insert($data);
    }

    /**
     * Get the import template url.
     *
     * @param int  $scope
     * @param null $args
     *
     * @return string
     */
    public function importTmpUrl($model)
    {
        $column = Schema::getColumnListing($model);
        Excel::create($model, function($excel)use ($column){
            $excel->sheet('sheet1', function($sheet)use ($column) {
                $sheet->fromArray($column);
                $sheet->row(1, function($row) {
                    $row->setAlignment('center');
                    $row->setFont(array(
                        'size'       => '12',
                    ));
                });

            });
        })->export('xls');
    }
}
